﻿//Handles specialized rendering tasks required by some tile

///<reference path="~/Scripts/scene.dataservice.js" />
///<reference path="~/Scripts/scene.startup.js" />
var tileFormatter = new function () {
    var previousPoint = null,
    //var tmplSizes = ['Small', 'Medium', 'Large'];

    formatNewGame = function(tileDiv) {
        //var scene = tileDiv.data().scenes[0];
        var btnSave = $('#btnSave');
        var grayDefense = $('#PlayerGrayDefense')[0];
        var grayAttack = $('#PlayerGrayAttack')[0];
        var blackDefense = $('#PlayerBlackDefense')[0];
        var blackAttack = $('#PlayerBlackAttack')[0];
        var grayPoints = $('#txtGrayPoints')[0];
        var blackPoints = $('#txtBlackPoints')[0];
        var login = startup.getLogin();
        var level = $('#gameLevel');

        $(".Player").dblclick(function() {
            if (grayDefense.innerHTML == "") {
                debugger;
                grayDefense.innerHTML = this.innerHTML;
                this.innerHTML = '';
                this.height = 0;
                this.remove();
            } else if (grayAttack.innerHTML == "") {
                grayAttack.innerHTML = this.innerHTML;
                this.innerHTML = '';
                this.height = 0;
                this.remove();
            } else if (blackAttack.innerHTML == "") {
                blackAttack.innerHTML = this.innerHTML;
                this.innerHTML = '';
                this.height = 0;
                this.remove();
            } else if (blackDefense.innerHTML == "") {
                blackDefense.innerHTML = this.innerHTML;
                this.innerHTML = '';
                this.height = 0;
                this.remove();
            }
        });

        btnSave.click(function() {
            if (!$.isNumeric(grayPoints.value) || !$.isNumeric(blackPoints.value)) {
                alert('Please enter a valid result of game.');
                return;
            }
            if (!grayDefense.innerHTML || !grayAttack.innerHTML || !blackDefense.innerHTML || !blackAttack.innerHTML) {
                alert('Please select players for game.');
                return;
            }

            dataService.saveNewGame(
                grayDefense.innerHTML,
                grayAttack.innerHTML,
                blackDefense.innerHTML,
                blackAttack.innerHTML,
                grayPoints.value,
                blackPoints.value,
                login,
                level.val(),
                newGameSaved);

            sceneStateManager.renderNewGame();
        });
    },
    
    formatLastGame = function (lastGameDiv) {
        var json = lastGameDiv.data().tileData;
        var tdWinners = $('#tdWinners');
        var tdLoosers = $('#tdLoosers');
        if (json) {
            var results = json['Result'].split(':');
            if (results[0].trim() == results[1].trim()) {
                tdWinners.html('Players 1:');
                tdLoosers.html('Players 2:');
                $('#tdWonPoints').html('Splitted points: ');
            }
        }
    },
        
    newGameSaved = function (data) {
        sceneStateManager.renderYourAccount();
        sceneStateManager.renderBestPlayers();
        sceneStateManager.renderLastGame();
        if ($.type(data) === "string") {
            alert(data);
        } else {
            alert('Game saved.');
        }
       
    },

    formatYourAccount = function (yourAccountDiv) {
        var tileId = yourAccountDiv.attr('id');

        if (Modernizr.canvas) {
            var canvasDiv = $('#' + tileId + 'Canvas');
            if (canvasDiv.length > 0) {
                canvasDiv.html('');
                //Render canvas
                var sceneId = sceneStateManager.getScene();
                var size = yourAccountDiv.data().scenes[sceneId].size;
                var heightMultiplier = (size == 1) ? .55 : .72;
                var width = yourAccountDiv.data().scenes[sceneId].width * .94;
                var height = yourAccountDiv.data().scenes[sceneId].height * heightMultiplier;
                var json = yourAccountDiv.data().tileData;
                renderCanvas(canvasDiv, width, height, 'Green', json['PointsHistory']);
            }
        }
    },
    
    renderCanvas = function (canvasDiv, width, height, color, dataPointsJson) {
        if (dataPointsJson != null && dataPointsJson.length > 0) {
            var quoteData = [];
            var maxY = 0;
            for (var i = 0; i < dataPointsJson.length; i++) {
                var pd = dataPointsJson[i];
                maxY = (pd.Points > maxY) ? pd.Points : maxY;
                quoteData.push([pd.TimeStamp, pd.Points]);
            }
            maxY = 1.3 * maxY;
            
            //Add plot()
            var chartOptions = {
                series: {
                    lines: { show: true, fill: true },
                    points: { show: true, radius: 5 }
                },
                grid: { hoverable: true, autoHighlight: true },
                legend: { position: 'se' },
                yaxis: { max: maxY, min: 0 },
                //xaxis: { minTickSize: [1, 'hour'], mode: 'time', timeformat: '%h %P', twelveHourClock: true }
                xaxis: {mode: "time", timeformat: "%m/%d/%y"}
            };

            canvasDiv.attr('style', 'width:' + width + 'px;height:' + height + 'px;');

            $.plot(canvasDiv, [{
                color: color,
                shadowSize: 4,
                label: (dataPointsJson.length == 100) ? 'Points (last 100 matches)' : 'Points of your matches',
                data: quoteData
            }], chartOptions);

            canvasDiv.bind('plothover', function(event, pos, item) {
                if (item) {
                    if (previousPoint != item.datapoint) {
                        previousPoint = item.datapoint;

                        $('#CanvasTooltip').remove();
                        var y = item.datapoint[1] + ' - ' + getDate(item.datapoint[0]);

                        showTooltip(item.pageX, item.pageY, y);
                    } else {
                        $("#CanvasTooltip").remove();
                        previousPoint = null;
                    }
                }
            });
        }
    },
        
    getDate = function (timeStamp) {
        var d = new Date(timeStamp);
        return (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear() + ' ' + ((d.getUTCHours() < 10) ? ("0" + d.getUTCHours()) : d.getUTCHours()) + ':' + ((d.getMinutes() < 10) ? ("0" + d.getMinutes()) : d.getMinutes());
    },

    showTooltip = function (x, y, contents) {
        $('<div id="CanvasTooltip">' + contents + '</div>').css({
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 15,
            border: '1px solid #000',
            padding: '2px',
            'background-color': '#fee',
            opacity: 0.80
        }).appendTo("body").fadeIn(200);
    };

    return {
        formatNewGame: formatNewGame,
        formatYourAccount: formatYourAccount,
        formatLastGame: formatLastGame,
    };

} ();